/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import moment from 'moment';
import { message } from 'antd';

function fixOrderDetailFormData(params) {
  const {
    formData: { timeRange, ...formData },
    showQuickJumper,
    showSizeChanger,
    total,
    current,
    ...rest
  } = params;
  let data = { ...rest, page: current };
  if (formData.orderId) {
    formData.orderId = formData.orderId
      .replace(/[\n,]/g, ',')
      .split(',')
      .filter(i => i)
      .join(',');
    data = { ...data, orderId: formData.orderId };
  }
  timeRange &&
    timeRange.forEach((item, index) => {
      const value = moment(item).format('YYYY-MM-DD HH:mm:ss');
      index === 0 && (data.start_time = value);
      index === 1 && (data.end_time = value);
    });
  data = { ...data, ...formData };
  return data;
}

function getOrderDetailsList(params, dispatch) {
  const data = fixOrderDetailFormData(params);
  const { start_time, end_time } = data;
  if (start_time && end_time) {
    const inMonth = moment(data.end_time).month() == moment(data.start_time).month();
    const inThirtyDay = moment().diff(moment(data.start_time), 'month') < 1;
    if (!inThirtyDay && !inMonth) {
      message.warn('查询1个月之前扫描记录不可跨月查询！');
      return;
    }
  }

  // eslint-disable-next-line consistent-return
  return dispatch({
    type: 'orderDetails/getOrderDetailsList',
    payload: { ...data },
  }).then(res => {
    const { list } = res;
    return { ...res, total: list.length };
  });
}

export { getOrderDetailsList, fixOrderDetailFormData };
